package com.gnerv.business.platform.service.impl;

import com.alibaba.fastjson.JSON;
import com.gnerv.business.platform.common.util.UUIDUtil;
import com.gnerv.business.platform.entity.Storage;
import com.gnerv.business.platform.service.StorageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * @description:
 * @author: Gnerv LiGen
 * @date: 2018-07-25
 **/
@Service
public class StorageServiceImpl implements StorageService {

    private final String FILE_INFO = "_info";

    @Value("${gnerv.business.storage.local.path}")
    private String localPath;

    @Override
    public Storage saveLocal(MultipartFile multipartFile) {
        Storage storage = new Storage();
        if (multipartFile.isEmpty()) {
            return storage;
        }
        try {
            byte[] bytes = multipartFile.getBytes();
            //获取MD5值
            String md5DigestAsHex = DigestUtils.md5DigestAsHex(bytes);
            //创建存储地址
            String storagePath = localPath + md5DigestAsHex;
            //保存文件
            Path path = Paths.get(storagePath);
            Files.write(path, bytes);
            //获取真实名字
            String originalFilename = multipartFile.getOriginalFilename();
            originalFilename = URLEncoder.encode(originalFilename, "utf-8");
            //获取后缀名
            String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //设置文件存储对象参数
            storage.setUuid(UUIDUtil.getLowerUUID());
            storage.setMd5(md5DigestAsHex);
            storage.setName(originalFilename);
            storage.setPath(storagePath);
            storage.setSize(multipartFile.getSize());
            storage.setSuffix(fileSuffix);
            //保存文件存储对象至文件
            String jsonString = JSON.toJSONString(storage);
            bytes = jsonString.getBytes();
            storagePath = localPath + md5DigestAsHex + FILE_INFO;
            path = Paths.get(storagePath);
            Files.write(path, bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return storage;
    }

    @Override
    public Storage getStorageByMd5(String md5) {
        String storagePath = localPath + md5 + FILE_INFO;
        Path path = Paths.get(storagePath);
        List<String> readLines = null;
        try {
            readLines = Files.readAllLines(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Storage storage = JSON.parseObject(readLines.get(0), Storage.class);
        File file = new File(localPath, md5);
        storage.setFile(file);
        return storage;
    }


}
